package xyz.jangle.thread.storage2;

import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jangle
 * @email 274676957@qq.com
 * 2025年8月3日 上午8:37:09
 */
public class Storage2 {
	
	
	private final Lock lock;
	
	private final Condition getCondition;
	
	private final Condition setCondition;
	
	private Queue<Date> queue;

	private int max;
	
	
	public Storage2() {
		super();
		lock = new ReentrantLock();
		getCondition = lock.newCondition();
		setCondition = lock.newCondition();
		queue = new LinkedList<Date>();
		max = 3;
	}


	public void get() {
		lock.lock();
		try{
			while(queue.size() == 0) {
				getCondition.await();
			}
			Date date = queue.poll();
			System.out.println("Get:"+date);
//			try {
//				TimeUnit.SECONDS.sleep(1);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			setCondition.signalAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
	
	public void set() {
		lock.lock();
		try {
			while(queue.size() == max) {
				setCondition.await();
			}
			Date date = new Date();
			System.out.println("Set:"+date);
			queue.offer(date);
//			try {
//				TimeUnit.SECONDS.sleep(1);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			getCondition.signalAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
	
	
	

}
